using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Controls
{
	public class NumericBox : TextBoxEx
	{
		public static readonly DependencyProperty MinValueProperty = DependencyProperty.Register("MinValue", typeof(double), typeof(NumericBox), new UIPropertyMetadata(double.MinValue));

		public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(double), typeof(NumericBox), new PropertyMetadata(double.MaxValue));

		public double MinValue
		{
			get
			{
				return (double)GetValue(MinValueProperty);
			}
			set
			{
				SetValue(MinValueProperty, value);
			}
		}

		public double MaxValue
		{
			get
			{
				return (double)GetValue(MaxValueProperty);
			}
			set
			{
				SetValue(MaxValueProperty, MaxValue);
			}
		}

		protected override void OnInitialized(EventArgs e)
		{
			base.TextAlignment = TextAlignment.Right;
			base.OnInitialized(e);
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.OnKeyDown(e);
			if (e.Key == Key.OemMinus || e.Key == Key.Subtract)
			{
				if (Text.IndexOf("-") != -1)
				{
					e.Handled = true;
				}
			}
			else if (e.Key == Key.Decimal || e.Key == Key.OemPeriod)
			{
				if (string.IsNullOrEmpty(Text))
				{
					Text = "0.";
					e.Handled = true;
				}
				else if (Text.IndexOf(".") != -1)
				{
					e.Handled = true;
				}
			}
			else if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.Tab || e.Key == Key.Back)
			{
				e.Handled = false;
			}
			else
			{
				e.Handled = true;
			}
		}

		protected override void OnTextChanged(TextChangedEventArgs e)
		{
			TextChange[] array = new TextChange[e.Changes.Count];
			e.Changes.CopyTo(array, 0);
			double num = 0.0;
			int offset = array[0].Offset;
			if (array[0].AddedLength > 0)
			{
				num = 0.0;
				if (Text == "-")
				{
					if (MinValue >= 0.0)
					{
						Text = Text.Remove(offset, array[0].AddedLength);
						Select(offset, 0);
					}
				}
				else if (double.TryParse(Text, out num))
				{
					if (num < MinValue || num > MaxValue)
					{
						Text = Text.Remove(offset, array[0].AddedLength);
						Select(offset, 0);
					}
					else
					{
						Select(Text.Length, 0);
					}
				}
				else
				{
					Text = Text.Remove(offset, array[0].AddedLength);
					Select(offset, 0);
				}
			}
			if (Text.Length == 0)
			{
				Text = "";
			}
			base.OnTextChanged(e);
		}
	}
}
